#include <iostream>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <functional>
#include <vector>
#include "ThreadPool.hpp"

// 引入线程池代码
// 假设前面的 ThreadPool 定义已在此文件中

class TcpServer
{
public:
    TcpServer(int port, size_t threadCount)
        : port(port), threadPool(ThreadPool::GetInstance(threadCount))
    {
    }

    void Start()
    {
        int serverFd = socket(AF_INET, SOCK_STREAM, 0);
        if (serverFd == -1)
        {
            perror("Socket creation failed");
            exit(EXIT_FAILURE);
        }

        sockaddr_in serverAddr{};
        serverAddr.sin_family = AF_INET;
        serverAddr.sin_addr.s_addr = INADDR_ANY;
        serverAddr.sin_port = htons(port);

        if (bind(serverFd, (sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
        {
            perror("Bind failed");
            close(serverFd);
            exit(EXIT_FAILURE);
        }

        if (listen(serverFd, 10) < 0)
        {
            perror("Listen failed");
            close(serverFd);
            exit(EXIT_FAILURE);
        }

        std::cout << "Server started on port " << port << "\n";

        while (true)
        {
            sockaddr_in clientAddr{};
            socklen_t clientLen = sizeof(clientAddr);
            int clientFd = accept(serverFd, (sockaddr *)&clientAddr, &clientLen);
            if (clientFd < 0)
            {
                perror("Accept failed");
                continue;
            }

            std::cout << "New connection from "
                      << inet_ntoa(clientAddr.sin_addr)
                      << ":" << ntohs(clientAddr.sin_port) << "\n";

            // 将任务提交给线程池处理
            threadPool->enqueue([clientFd]()
                                { HandleClient(clientFd); });
        }

        close(serverFd);
    }

private:
    static void HandleClient(int clientFd)
    {
        char buffer[1024];
        while (true)
        {
            memset(buffer, 0, sizeof(buffer));
            ssize_t bytesRead = recv(clientFd, buffer, sizeof(buffer) - 1, 0);
            if (bytesRead <= 0)
            {
                std::cout << "Client disconnected\n";
                break;
            }

            std::cout << "Received: " << buffer;

            std::string response = "Echo: " + std::string(buffer);
            send(clientFd, response.c_str(), response.size(), 0);
        }

        close(clientFd);
    }

    int port;
    ThreadPool *threadPool;
};

int main()
{
    TcpServer server(8080, 4); // 监听8080端口，4个线程
    server.Start();
    return 0;
}
